﻿#pragma once
#include "Player.h"
#include <QTcpServer>
#include <QMutex>
#include <QTimerEvent>


class Server : public QTcpServer
{
	Q_OBJECT
public:
    ~Server(void);

	bool Start(int port);

    //单例类
    static Server* Instance()
    {
        static Server m;
        return &m;
    }

    //新增玩家
	bool Add(Player* p);

    //删除玩家
	bool Remove(const QString name);
	bool Remove(Player* p);

    //查询玩家
	Player* Find(const QString name);

    //统计某个房间内的玩家数
    int CountPlayersInRoom(int nRoom);
	void CountPlayerInRoom(int room, ROOM_STATE& s);

	void CheckHeartbeat();

    //向所有在线玩家发送当前所有房间人数状态
    void UpdateRoomState();


signals:
	void sigLog(QString text);

protected:
	void timerEvent(QTimerEvent* e);

public slots:
	void slotNewConnection();
	void slotRecvMsg(char *pData, int nDataLen);

private:
	Server(void);

	//处理接收到的玩家TCP消息
	void OnMsg(Player* p, MSG_HEADER* pHeader, char *pData, int nDataLen);
	void OnMsgLogon(Player* player, MSG_HEADER *pHeader);       //玩家申请登陆
	void OnMsgMove(Player* player, MSG_HEADER* pHeader);        //走棋
	void OnMsgSuccess(Player* player, MSG_HEADER* pHeader);     //胜利
	void OnMsgSay(Player* player, MSG_HEADER* pHeader);         //说话
	void OnMsgHeartBeat(Player* player, MSG_HEADER* pHeader);   //心跳

	void Log(QString text);


private:
    QList<Player*> mPlayers;
    QMutex mMutex;
	ROOM_STATE mRoom[FIR_MAX_ROOM];

	int mTimerUpdateRoomState;
	int mTimerCheckHeartbeat;

};

